package thinkinjava4.ch17_containers;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimePullMultipart;

import java.util.*;

public class SimpleHashMap<K, V> extends AbstractMap<K, V> {
    static final int SIZE = 997;
    //散列位数组
    LinkedList<MapEntry<K, V>>[] buckets = new LinkedList[SIZE];

    public V put(K key, V value) {
        V oldValue = null;
        //获取散列位下标
        int index = Math.abs(key.hashCode()) % SIZE;
        //当前下标没有List则新建List
        if (buckets[index] == null)
            buckets[index] = new LinkedList<>();
        //取得List
        LinkedList<MapEntry<K, V>> bucket = buckets[index];
        //新建键值对
        MapEntry<K, V> pair = new MapEntry<>(key, value);
        //查找标记
        boolean found = false;
        ListIterator<MapEntry<K, V>> it = bucket.listIterator();
        //在当前散列位下查找键值对
        while (it.hasNext()) {
            MapEntry<K, V> iPair = it.next();
            if (iPair.getKey().equals(key)) {
                oldValue = iPair.getValue();
                it.set(pair);
                found = true;
                break;
            }
        }
        if (!found) {
            buckets[index].add(pair);
        }
        return oldValue;
    }

    public V get(Object key) {
        int index = Math.abs(key.hashCode()) % SIZE;
        if (buckets[index] == null) return null;
        for (MapEntry<K, V> iPair : buckets[index])
            if (iPair.getKey().equals(key))
                return iPair.getValue();
        return null;
    }


    /**
     * 键值对集合
     *
     * @return
     */
    @Override
    public Set<Entry<K, V>> entrySet() {
        Set<Map.Entry<K, V>> set = new HashSet<>();
        for (LinkedList<MapEntry<K, V>> bucket : buckets) {
            if (bucket == null)
                continue;
            for (MapEntry<K, V> mPair : bucket)
                set.add(mPair);
        }
        return set;
    }

    public static void main(String[] args) {
        SimpleHashMap<String, String> m = new SimpleHashMap<>();
        m.put("a", "aValue");
        m.put("b", "bValue");
        System.out.println(m);
    }
}
